import Axios from "axios";
import { serverConfig, basePath } from "../config/apiConfig";
import { setCrypto, getCrypto } from "./cryptoTool";
import { Message, Loading } from "element-ui";
import { requestLevel } from "../config/baseConfig";
import Storage from "./storage";
import { clearHistory } from "./router";
import { StorageName } from "../config/localStorage";
const { success, warn, fail, error, loginTimeOut } = requestLevel;
let _vm = null;
Axios.getVM = function(vm) {
  //获取vue实例
  _vm = vm;
};
Axios.defaults.baseURL = basePath; //默认请求地址
Axios.defaults.timeout = serverConfig.RequestTimeOut; //请求超时
// 添加请求拦截器
let loadState;
Axios.interceptors.request.use(
  function(config) {
    _vm.$store.state.requestState = true; //请求状态
    loadState = Loading.service({
      text: "加载中...",
    });
    // 在发送请求之前做些什么
    switch (config.method) {
      case "get":
      case "delete":
        config.params.token = _vm.$storage.getStorage(StorageName.Token);
        config.params = { params: setCrypto(config.params) };
        break;
      case "post":
      case "put":
      case "patch":
        config.data.params.token = _vm.$storage.getStorage(StorageName.Token);
        config.data.params = setCrypto(config.data?.params);
        break;
    }
    return config;
  },
  function(error) {
    _vm.$store.state.requestState = false; //请求状态
    loadState.close();
    Message.error("请求失败");
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
// 添加响应拦截器
Axios.interceptors.response.use(
  function({ data: { params } }) {
    const _data = getCrypto(params);
    _vm.$store.state.requestState = false; //请求状态
    loadState.close();
    // 对响应数据做点什么
    switch (_data.result) {
      case success:
        _data.msg && Message.success(_data.msg);
        return _data;
      case warn:
        _data.msg && Message.info(_data.msg);
        break;
      case fail:
        _data.msg && Message.warning(_data.msg);
        break;
      case error:
        _data.msg && Message.error(_data.msg);
        break;
      case loginTimeOut:
        _data.msg && Message.error(_data.msg);
        Storage.clearStorage(); //清除之前的数据
        clearHistory(_vm.$router);
        _vm.$router.replace("/login");
        break;
      default:
        _data.msg && Message.info(_data.msg);
        break;
    }
  },
  function(error) {
    _vm.$store.state.requestState = false; //请求状态
    loadState.close();
    Message.error("加载失败");
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

export default Axios;
